package com.cpe.transfer.student;

import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import com.cpe.data.domain.student.Student;
import com.cpe.data.domain.student.StudentForm;
import com.cpe.data.domain.student.StudentInfo;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.util.math.CalcUtil;

import jodd.util.StringUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class StudentTransfer {
	/**
	 * 表单-->实体
	 */
	public Student toEntity(StudentForm form) {
		Assert.notNull(form);
		Student Student = new Student();
		BeanUtils.copyProperties(form, Student);
		return Student;
	}

	/**
	 * 表单-->实体
	 */
	public Student toUpdateEntity(Student student, StudentForm form) {
		Assert.notNull(form);
		Assert.notNull(student);
		// 可以置空
		if (!Objects.equal(student.getParentId(), form.getParentId())) {
			student.setParentId(form.getParentId());
		}
		if (!Objects.equal(student.getParentMobile(), form.getParentMobile())) {
			student.setParentMobile(form.getParentMobile());
		}

		// 不可置空
		if (StringUtil.isNotBlank(form.getName()) && !Objects.equal(student.getName(), form.getName())) {
			student.setName(form.getName());
		}
		if (form.getBirthday() != null && !Objects.equal(student.getBirthday(), form.getBirthday())) {
			student.setBirthday(form.getBirthday());
		}
		if (form.getSex() != null && !Objects.equal(form.getSex(), student.getSex())) {
			student.setSex(form.getSex());
		}
		return student;
	}

	/**
	 * 实体分页-->响应分页
	 */
	public PageInfo<StudentInfo> toPageInfo(List<Student> students) {
		Assert.notNull(students);
		PageInfo<Student> pageInfo = new PageInfo<>(students);
		PageInfo<StudentInfo> pageResp = new PageInfo<>();
		BeanUtils.copyProperties(pageInfo, pageResp);
		List<StudentInfo> infoList = Lists.newArrayList();
		for (Student student : students) {
			infoList.add(toInfo(student));
		}
		pageResp.setList(infoList);
		return pageResp;
	}

	/**
	 * 实体-->响应
	 */
	public StudentInfo toInfo(Student student) {
		Assert.notNull(student);
		StudentInfo info = new StudentInfo();
		BeanUtils.copyProperties(student, info);
		info.setSex(student.getSex() == 0 ? "男" : "女");
		// 计算年龄
		Date birthday = student.getBirthday();
		info.setAge(CalcUtil.getRealAge(birthday));
		// 班级
		info.setClassName(student.getClassId());
		log.debug("info = " + info);
		return info;
	}

	/**
	 * 实体集-->响应集
	 */
	public List<StudentInfo> toInfoList(List<Student> students) {
		Assert.notNull(students);
		List<StudentInfo> infoList = Lists.newArrayList();
		for (Student student : students) {
			infoList.add(toInfo(student));
		}
		return infoList;
	}
}
